package com.fingard.dsp.bank.directbank.jxb01;

import com.fingard.FGBiz;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.math.BigDecimal;
import java.sql.Connection;

/**
 * 嘉兴银行单笔付款查询
 * Created by F on 2019/08/07
 */
public class JXB01SinglePay extends JXB01Base implements ISinglePay {
    /**
     * 支付
     * @param p_req1908
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        RetAtsSingle retAtsSingle = new RetAtsSingle(p_req1908.reqHeader);
        RetAtsSglDetail detail = new RetAtsSglDetail();
        Connection conn= FGBiz.getLocalDbConn();
        try{
            //======拼接报文======
            //拼接请求报文体
            JXB01Header header = new JXB01Header();
            if("1".equals(p_req1908.singleDetail.sameBnk)){//同行
                header.trsCode="B2EBankInnerTransfer";
            }else if("0".equals(p_req1908.singleDetail.sameBnk)){//他行
                header.trsCode="B2ECrossBankTransfer";
            }
            XmlTextWriter xmlReq = new XmlTextWriter();
            writeReqHeader(xmlReq,header);
            xmlReq.writeElementString("ERPJnlNo",p_req1908.singleDetail.askNumber);//客户流水号
            xmlReq.writeEndElement();
            XElement body =new XElement("Body","");
            body.addChild(new XElement("PayerAcNo",p_req1908.singleDetail.payAct));//转出账号
            body.addChild(new XElement("PayeeAcNo",p_req1908.singleDetail.recAct));//收款账号
            body.addChild(new XElement("PayeeAcName",p_req1908.singleDetail.recName));//收款人帐户名称
            body.addChild(new XElement("Amount",p_req1908.singleDetail.payAmount));//付款金额
            body.addChild(new XElement("Remark",p_req1908.singleDetail.purpose));//用途
            if("0".equals(p_req1908.singleDetail.sameBnk)){
                body.addChild(new XElement("PayerAcName",p_req1908.singleDetail.payName));//付款人名称
                body.addChild(new XElement("Currency",convertCurToBank(p_req1908.singleDetail.payCur)));//付款人币种
                body.addChild(new XElement("UnionDeptId",p_req1908.singleDetail.cnapsCode));//转入行清算行号
                String priority="2";//转账方式 1：一般汇款(大额) 2：小额快汇
                String urgentFlag = getBankConfig().getValueAsString("UrgentLargeAmount");
                if (StringHelper.hasAnyChar(urgentFlag)) {
                    if ((new BigDecimal(p_req1908.singleDetail.payAmount)).compareTo(new BigDecimal(urgentFlag)) > 0) {
                        priority = "1";
                    }
                }
                body.addChild(new XElement("Priority",priority));
                body.addChild(new XElement("TransAlias","0"));//到账时间 0：实时 1：普通 2：次日
            }
            nodeAnalysis(p_req1908.singleDetail.srcXElement,body,getCharset());
            xmlReq.writeXElement(body);
            xmlReq.writeEndDocument();
            //======拼接报文======
            //发送请求报文
            String[] bankResult = sendToBank(xmlReq.toXmlString(),header.trsCode);
            //处理响应报文
            if(bankResult[0].length()==0){
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpSbMsg);
                if(tmpBkReader!=null){
                    String respCode = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");
                    String respInfo = tmpBkReader.getFirstText("/Message/Head/IBSReturnMsg");
                    if("000000".equals(respCode)){
                        String trsStatus=tmpBkReader.getFirstText("/Message/Body/TrsStatus");
                        String returnCode=tmpBkReader.getFirstText("/Message/Body/ReturnCode");
                        //1、ReturnCode不存在，状态未知，需人工确认
                        //2、ReturnCode存在且返回000000，表示交易成功
                        //3、ReturnCode存在但返回非000000时，需判断TrsStatus的值，当TranStatus的值为1、2、3时，可以确认交易失败
                        //4、其它中间状态均需要人工确认，银行不提供状态查询的接口
                        if(StringHelper.hasAnyChar(returnCode)){
                            detail.respCode = "0";
                            detail.respInfo = tmpBkReader.getFirstText("/Message/Body/ReturnMsg");
                            detail.reqSeqID = p_req1908.singleDetail.askNumber;
                            if("000000".equals(returnCode)){
                                detail.transState=returnCode+"+"+trsStatus;
                            }else {
                                detail.transState=trsStatus;
                            }
                            detail.payInfoCode = detail.transState;
                            detail.transAmt = tmpBkReader.getFirstText("/Message/Body/Amount");
                        }else {
                            detail.respCode ="-1";
                            detail.respInfo = "返回的ReturnCode不存在";
                        }
                    }else {
                        detail.respCode ="-1";
                        detail.respInfo = respInfo;
                    }
                }else{
                    detail.respCode ="-1";
                    detail.respInfo = tmpSbMsg.toString();
                }
            }else if (bankResult[0].equals(ConnState.FAIL)) {
                detail.respCode = "0";
                detail.respInfo = bankResult[1];
                detail.reqSeqID = p_req1908.singleDetail.askNumber;
                detail.transState = PaymentState.FAIL_Payment;
                detail.payInfoCode = bankResult[0];
            }else{
                detail.respCode ="-1";
                detail.respInfo = bankResult[1];
                detail.reqSeqID = p_req1908.singleDetail.askNumber;
            }
        }catch (Exception e){
            detail.respCode = "-1";
            detail.respInfo = e.getMessage();
            e.printStackTrace();
        }finally {
            conn.close();
        }
        retAtsSingle.writeRetDetail(detail);
        return retAtsSingle;
    }

    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        return null;
    }

    /**
     * 查询支付结果
     * @param p_req1944
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
        //此接口只是查网银的处理结果，不表示最终转账结果，银行暂无法提供最终状态查询接口
        /*RetAtsSingle retAtsSingle = new RetAtsSingle(p_req1944.reqHeader);
        RetAtsSglDetail detail = new RetAtsSglDetail();
        try{
            //======拼接报文======
            //拼接请求报文体
            JXB01Header header = new JXB01Header();
            header.trsCode="B2ETrsResultQry";
            XmlTextWriter xmlReq = new XmlTextWriter();
            writeReqHeader(xmlReq,header);
            xmlReq.writeElementString("TRANSDATE",p_req1944.bgnDate.substring(0,10));//交易日期
            String tranCode="";
            if("1".equals(p_req1944.sameBnk)){
                tranCode="B2EBankInnerTransfer";
            }else if("0".equals(p_req1944.sameBnk)){
                tranCode="B2ECrossBankTransfer";
            }
            xmlReq.writeElementString("TRANSCODE",tranCode);//交易类型
            xmlReq.writeEndElement();
            XElement body =new XElement("Body","");
            body.addChild(new XElement("ERPJnlNo", p_req1944.askNumber));//交易流水号
            xmlReq.writeXElement(body);
            xmlReq.writeEndDocument();
            //======拼接报文======
            //发送请求报文
            String[] bankResult = sendToBank(xmlReq.toXmlString(),header.trsCode);
            if (bankResult[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String respCode = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");
                    String respInfo = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");
                    if ("000000".equals(respCode)) {//交易成功
                        detail.respCode = "0";
                        detail.respInfo = tmpBkReader.getFirstText("/Message/Body/List/Map/ReturnMsg");
                        detail.reqSeqID = p_req1944.askNumber;
                        detail.transState = tmpBkReader.getFirstText("/Message/Body/List/Map/JnlState");
                        detail.payInfoCode = detail.transState;
                        detail.transAmt = tmpBkReader.getFirstText("/Message/Body/Amount");
                    }else {
                        detail.respCode = "-1";
                        detail.respInfo = respInfo;
                    }
                }else {
                    detail.respCode = "-1";
                    detail.respInfo = tmpSbMsg.toString();
                }
            }else {
                detail.respCode = "-1";
                detail.respInfo = bankResult[1];
            }
        }catch (Exception e){
            detail.respCode = "-1";
            detail.respInfo = e.getMessage();
            e.printStackTrace();
        }
        retAtsSingle.writeRetDetail(detail);
        return retAtsSingle;*/
        return null;
    }

    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
        return null;
    }
}
